/**
 * <签名算法工具类>
 * <p>
 * <签名算法js版本，提供给前端，后端SignAlgorithmUtils类，第三方需要直接下载jar>
 * 
 * @author 欧增奇
 * @version [版本号, 2017年8月16日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
;
!function(window, undefined)
{
    "use strict";

    var $, ready = {};

    window.sign = {
        // 提供给外部创建签名
        createSign : function(params)
        {
            return $.sign.createSign(params);
        }
    };

    // 编码
    var Base64 = function()
    {
        // private property
        var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

        // public method for encoding
        this.encode = function(input)
        {
            var output = "";
            var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
            var i = 0;
            input = _utf8_encode(input);
            while (i < input.length)
            {
                chr1 = input.charCodeAt(i++);
                chr2 = input.charCodeAt(i++);
                chr3 = input.charCodeAt(i++);
                enc1 = chr1 >> 2;
                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                enc4 = chr3 & 63;
                if (isNaN(chr2))
                {
                    enc3 = enc4 = 64;
                } else if (isNaN(chr3))
                {
                    enc4 = 64;
                }
                output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
            }
            return output;
        }

        // public method for decoding
        this.decode = function(input)
        {
            var output = "";
            var chr1, chr2, chr3;
            var enc1, enc2, enc3, enc4;
            var i = 0;
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
            while (i < input.length)
            {
                enc1 = _keyStr.indexOf(input.charAt(i++));
                enc2 = _keyStr.indexOf(input.charAt(i++));
                enc3 = _keyStr.indexOf(input.charAt(i++));
                enc4 = _keyStr.indexOf(input.charAt(i++));
                chr1 = (enc1 << 2) | (enc2 >> 4);
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
                chr3 = ((enc3 & 3) << 6) | enc4;
                output = output + String.fromCharCode(chr1);
                if (enc3 != 64)
                {
                    output = output + String.fromCharCode(chr2);
                }
                if (enc4 != 64)
                {
                    output = output + String.fromCharCode(chr3);
                }
            }
            output = _utf8_decode(output);
            return output;
        }

        // private method for UTF-8 encoding
        var _utf8_encode = function(string)
        {
            string = string.replace(/\r\n/g, "\n");
            var utftext = "";
            for (var n = 0; n < string.length; n++)
            {
                var c = string.charCodeAt(n);
                if (c < 128)
                {
                    utftext += String.fromCharCode(c);
                } else if ((c > 127) && (c < 2048))
                {
                    utftext += String.fromCharCode((c >> 6) | 192);
                    utftext += String.fromCharCode((c & 63) | 128);
                } else
                {
                    utftext += String.fromCharCode((c >> 12) | 224);
                    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                    utftext += String.fromCharCode((c & 63) | 128);
                }

            }
            return utftext;
        }

        // private method for UTF-8 decoding
        var _utf8_decode = function(utftext)
        {
            var string = "";
            var i = 0;
            var c = c1 = c2 = 0;
            while (i < utftext.length)
            {
                c = utftext.charCodeAt(i);
                if (c < 128)
                {
                    string += String.fromCharCode(c);
                    i++;
                } else if ((c > 191) && (c < 224))
                {
                    c2 = utftext.charCodeAt(i + 1);
                    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                    i += 2;
                } else
                {
                    c2 = utftext.charCodeAt(i + 1);
                    c3 = utftext.charCodeAt(i + 2);
                    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
            return string;
        }
    };

    // 编码
    var Md5 = function()
    {
        /*
         * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message Digest Algorithm, as defined in RFC 1321. Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet Distributed under the BSD License See http://pajhome.org.uk/crypt/md5 for more info.
         */

        /*
         * Configurable variables. You may need to tweak these to be compatible with the server-side, but the defaults work in most cases.
         */
        var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
        var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
        var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */

        /*
         * These are the functions you'll usually want to call They take string arguments and return either hex or base-64 encoded strings
         */
        this.hex_md5 = function(s)
        {
            return binl2hex(core_md5(str2binl(s), s.length * chrsz));
        }
        this.b64_md5 = function(s)
        {
            return binl2b64(core_md5(str2binl(s), s.length * chrsz));
        }
        this.str_md5 = function(s)
        {
            return binl2str(core_md5(str2binl(s), s.length * chrsz));
        }
        this.hex_hmac_md5 = function(key, data)
        {
            return binl2hex(core_hmac_md5(key, data));
        }
        this.b64_hmac_md5 = function(key, data)
        {
            return binl2b64(core_hmac_md5(key, data));
        }
        this.str_hmac_md5 = function(key, data)
        {
            return binl2str(core_hmac_md5(key, data));
        }

        /*
         * Calculate the MD5 of an array of little-endian words, and a bit length
         */
        function core_md5(x, len)
        {
            /* append padding */
            x[len >> 5] |= 0x80 << ((len) % 32);
            x[(((len + 64) >>> 9) << 4) + 14] = len;

            var a = 1732584193;
            var b = -271733879;
            var c = -1732584194;
            var d = 271733878;

            for (var i = 0; i < x.length; i += 16)
            {
                var olda = a;
                var oldb = b;
                var oldc = c;
                var oldd = d;

                a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936);
                d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586);
                c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819);
                b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330);
                a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897);
                d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426);
                c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341);
                b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983);
                a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416);
                d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417);
                c = md5_ff(c, d, a, b, x[i + 10], 17, -42063);
                b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162);
                a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682);
                d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101);
                c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290);
                b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329);

                a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510);
                d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632);
                c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713);
                b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302);
                a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691);
                d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083);
                c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335);
                b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848);
                a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438);
                d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690);
                c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961);
                b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501);
                a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467);
                d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784);
                c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473);
                b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734);

                a = md5_hh(a, b, c, d, x[i + 5], 4, -378558);
                d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463);
                c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562);
                b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556);
                a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060);
                d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353);
                c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632);
                b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640);
                a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174);
                d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222);
                c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979);
                b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189);
                a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487);
                d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835);
                c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520);
                b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651);

                a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844);
                d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415);
                c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905);
                b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055);
                a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571);
                d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606);
                c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523);
                b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799);
                a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359);
                d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744);
                c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380);
                b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649);
                a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070);
                d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379);
                c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259);
                b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551);

                a = safe_add(a, olda);
                b = safe_add(b, oldb);
                c = safe_add(c, oldc);
                d = safe_add(d, oldd);
            }
            return Array(a, b, c, d);

        }

        /*
         * These functions implement the four basic operations the algorithm uses.
         */
        function md5_cmn(q, a, b, x, s, t)
        {
            return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b);
        }
        function md5_ff(a, b, c, d, x, s, t)
        {
            return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
        }
        function md5_gg(a, b, c, d, x, s, t)
        {
            return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
        }
        function md5_hh(a, b, c, d, x, s, t)
        {
            return md5_cmn(b ^ c ^ d, a, b, x, s, t);
        }
        function md5_ii(a, b, c, d, x, s, t)
        {
            return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
        }

        /*
         * Calculate the HMAC-MD5, of a key and some data
         */
        function core_hmac_md5(key, data)
        {
            var bkey = str2binl(key);
            if (bkey.length > 16)
                bkey = core_md5(bkey, key.length * chrsz);

            var ipad = Array(16), opad = Array(16);
            for (var i = 0; i < 16; i++)
            {
                ipad[i] = bkey[i] ^ 0x36363636;
                opad[i] = bkey[i] ^ 0x5C5C5C5C;
            }

            var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
            return core_md5(opad.concat(hash), 512 + 128);
        }

        /*
         * Add integers, wrapping at 2^32. This uses 16-bit operations internally to work around bugs in some JS interpreters.
         */
        function safe_add(x, y)
        {
            var lsw = (x & 0xFFFF) + (y & 0xFFFF);
            var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
            return (msw << 16) | (lsw & 0xFFFF);
        }

        /*
         * Bitwise rotate a 32-bit number to the left.
         */
        function bit_rol(num, cnt)
        {
            return (num << cnt) | (num >>> (32 - cnt));
        }

        /*
         * Convert a string to an array of little-endian words If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
         */
        function str2binl(str)
        {
            var bin = Array();
            var mask = (1 << chrsz) - 1;
            for (var i = 0; i < str.length * chrsz; i += chrsz)
                bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32);
            return bin;
        }

        /*
         * Convert an array of little-endian words to a string
         */
        function binl2str(bin)
        {
            var str = "";
            var mask = (1 << chrsz) - 1;
            for (var i = 0; i < bin.length * 32; i += chrsz)
                str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask);
            return str;
        }

        /*
         * Convert an array of little-endian words to a hex string.
         */
        function binl2hex(binarray)
        {
            var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
            var str = "";
            for (var i = 0; i < binarray.length * 4; i++)
            {
                str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF);
            }
            return str;
        }

        /*
         * Convert an array of little-endian words to a base-64 string
         */
        function binl2b64(binarray)
        {
            var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            var str = "";
            for (var i = 0; i < binarray.length * 4; i += 3)
            {
                var triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF);
                for (var j = 0; j < 4; j++)
                {
                    if (i * 8 + j * 6 > binarray.length * 32)
                        str += b64pad;
                    else
                        str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F);
                }
            }
            return str;
        }
    };

    // 签名工具类
    var Sign = function()
    {
    };
    Sign.pt = Sign.prototype;

    // base64
    Sign.pt.base64 = new Base64();

    // md5
    Sign.pt.md5 = new Md5();

    // 创建签名
    Sign.pt.createSign = function(params)
    {
        // 参数数组
        var objArr = [];

        if (!$.isEmptyObject(params))
        {
            for (var key in params)
            {
                objArr.push(key);
            }
        }
        // objArr.push('timestamp=' + new Date().getTime());

        // 排序 小到大
        objArr.sort();

        // 拼接参数
        var sign = "";
        for (var i = 0; i < objArr.length; i++)
        {
            var key = objArr[i] + "";
            var value = params[key] + "";
            sign += (sign.length > 0 ? '&' : '') + encodeURIComponent(key) + '=' + encodeURIComponent(value);
        }
        // 解决空白问题
        sign = sign.replace(/%20/g, '+');
        // console.log(sign);

        // md5
        sign = this.md5.hex_md5(sign);

        // 位移
        sign = this.shift(sign, false, 3);

        // base64
        sign = this.base64.encode(sign).replace(/=/g, "");
        // console.log(sign);
        return sign;
    };

    // 字符串右/左位移
    // @param strSrc 待位移的字符串
    // @param direction 待位移的方向（true：左，false：右；默认：false）
    // @param index 待位移的多少位
    // @return 返回位移好的字符串
    Sign.pt.shift = function(strSrc, direction, index)
    {
        var sbu = "";
        // 将字符串中的每一位字符存储到字符数组中。
        for (var x = 0; x < strSrc.length; x++)
        {
            var tempChar = strSrc.charCodeAt(x);
            if ($.isEmptyObject(direction) || !direction)
            {
                tempChar = tempChar >> index;
            } else
            {
                tempChar = tempChar << index;
            }
            sbu += String.fromCharCode(tempChar);
        }
        return sbu;
    };

    // 主入口
    ready.run = function()
    {
        $ = jQuery;
        $.sign = new Sign();
    };
    ready.run();
}(window);

/**
 * 欧增奇 http://www.ouzengqi.com
 */
;// 采用闭包标准模式开发
!function(window, undefined)
{
    "use strict";

    var $, ready = {};

    // 提供外部使用的方法
    window.ozq = {
        // 版本号
        v      : 'cache-2.0.0',
        // 模块名称
        module : 'ozq',
        // 模式,true，开发者模式，false,生产模式
        mode   : true,
        // 公共缓存时间设定
        caches : {
            // 缓存过期时间(单位天)
            overdueDay         : 10,
            // 缓存过期时间(单位毫秒)
            overdueMillisecond : 1000 * 60 * 10
        },
        // 后台url地址
        urls   : {
            // QQ登录查询用户
            getUser            : '/login/qq/get',
            // 查询用户信息
            listSysUserPage    : '/sys/ajaxListPage/sysUser/do',
            // 添加文章
            addSysArticle      : '/sys/add/sysArticle/do',
            // 文章分类
            listSysType        : '/sys/ajaxList/sysType/do',
            // 文章
            listSysArticlePage : '/sys/ajaxListPage/sysArticle/do',
            // 动态
            listSysDynamicPage : '/sys/ajaxListPage/sysDynamic/do',
            // 添加动态
            addSysDynamic      : '/sys/add/sysDynamic/do',
            // 作品
            listSysWorkPage    : '/sys/ajaxListPage/sysWork/do',
            // 添加作品
            addSysWork         : '/sys/add/sysWork/do',
            // 添加评论或留言
            addSysComment      : '/sys/add/sysComment/do',
            // 查询评论或留言
            listSysCommentPage : '/sys/ajaxListPage/sysComment/do',
            // 查询评论最多的用户
            listSysComment     : '/sys/ajaxList/sysComment/do',
            // 更新缓存
            updateCache        : '/update/cache/do'
        },
        // 初始化界面
        initUI : function()
        {
            // 清理老数据库
            $.ozq.clearOldData();

            // 初始化我要打赏页面
            $.ozq.initReward();

            // 初始化登录状态
            $.ozq.changeLogin();

            // 到底部
            // $.ozq.setFooter();

            // 首页轮播图
            $.ozq.initMainCarousel();

            // 到顶部工具
            $.ozq.initUtilTop();

            // 初始化编辑器
            layeditIndex = $.ozq.initEdit(KEY_MESSAGE_EDITOR);

            // 刷新code
            $.ozq.toolCodeRender();

            // 初始化界面事件
            $.ozq.initEvent();

            // 图片懒加载
            $.ozq.initLazyimg();
        }
    };

    // 常量元素
    // key
    var fingerprint = new Fingerprint().get(), KEY_COMMON_PAGE = "ozq-common-page", KEY_VALIDATE_SHOW = "ozq-validate-show", KEY_MESSAGE_EDITOR = "ozq_message_editor", KEY_PAGE_CURR = "pageCurr"
    // 其他
    , RAG_KEY = 'html', RAG_TOOL_TYPE_KEY = 'tool-type'
    // 自定义属性
    , DATA_OZQ_TYPE = 'data-ozq-type'
    // 元素
    , ELE_OZQ_FOOTER = '.ozq-footer', ELE_OZQ_HOT_BLOG = '.ozq-hot-blog', ELE_OZQ_RECOMMEND_BLOG = '.ozq-recommend-blog', ELE_OZQ_NEW_BLOG = '.ozq-new-blog', ELE_OZQ_HOT_USER = '.ozq-hot-user', ELE_OZQ_USER_REPLY = '.ozq-user-reply', ELE_OZQ_COMMENT = '.ozq-comment', ELE_OZQ_ARTICLE = '.ozq-article', ELE_OZQ_MESSAGE = '.ozq-message', ELE_OZQ_VALIDATE = '.ozq-validate', ELE_OZQ_IMG = '.ozq-img', ELE_OZQ_ADD_ARTICLE = '.ozq-add-article', ELE_ARTICLE_CLICK_BORDER = '.ozq-article-click-border', ELE_DBLCLICK_EDIT = '.ozq-dblclick-edit', ELE_ARTICLE_PROMPT = '.ozq-article-prompt', ELE_MAIN_CAROUSEL = '#main-carousel', ELE_LOGIN_QQ = '.ozq-login-qq', ELE_NAV = '.ozq-nav', ELE_NAV_ITEM = '.layui-nav-item', ELE_LAYUI_THIS = '.layui-this', ELE_NAV_AVATAR = '.ozq-nav-avatar', ELE_NAV_USER = '.ozq-nav-user', ELE_ARTICLE_TOOL_STYLE = '.ozq-article-tool-style', ELE_ARTICLE_TOOL = '.ozq-article-tool', ELE_NEW_USER = '.ozq-new-user', ELE_TYPE_BLOG = '.ozq-type-blog', ELE_ARTICLE_CONTENT = '.ozq-article-content'
    // 用户中心
    , HTML_OZQ_USER_INFO = '<img src="{{ d.userFigureUrl }}" alt="{{ d.userNickName }}"><h1>{{ d.userNickName }}</h1><p><span>{{ util.timeAgo(d.userRegisterTime) }} 加入</span></p><div class="ozq-user-tool">{{# if(d.userId==1){ }}<button class="layui-btn layui-btn-small ozq-update">更新服务缓存</button>{{# } }}<button class="layui-btn layui-btn-small ozq-local-update">更新本地缓存</button><button class="layui-btn layui-btn-danger layui-btn-small ozq-quit">注销登录</button></div>'
    // 首页-最新用户
    , HTML_OZQ_NEW_USER = '<dl>{{# layui.each(d.data.sysUsers, function(index, item){ }}<dd><a title="{{ item.userNickName }}"><img lay-src="{{ item.userFigureUrl }}" alt="{{ item.userNickName }}"><cite>{{ item.userNickName }}</cite></a></dd>{{# }); }}</dl>'
    // 首页-轮播图
    , HTML_OZQ_CAROUSEL = '<div carousel-item>{{# layui.each(d.data.sysArticles, function(index, item){ }}{{# if(item.article_cover_url.length > 0){ }}<div><a href="/detail/{{ item.article_code }}.html"><img lay-src="{{ item.article_cover_url }}" alt="{{ item.article_title }}"></a></div>{{# } }}{{# }); }}</div>'
    // 文章分类
    , HTML_OZQ_TYPE = '<div>{{# layui.each(d.data, function(index, item){ }}<a href="/share/share.html#!type={{ item.typeCode }}" data-type-code="{{ item.typeCode }}" class="layui-btn layui-btn-primary">{{ item.typeName }}</a>{{# }); }}</div>'
    // 文章
    , HTML_OZQ_ARTICLE = '<ul id="ozq-main-article">{{# layui.each(d.data.sysArticles, function(index, item){ }}<li class="ozq-block"><div class="layui-row layui-col-space10"> {{# if(item.article_cover_url.length > 0){ }}<div class="layui-col-xs4 layui-col-md3"><img lay-src="{{ item.article_cover_url }}" alt="{{ item.article_title }}"></div><div class="layui-col-xs8 layui-col-md9">{{# }else{ }}<div>{{# } }}<p class="layui-elip">{{# if(item.article_click > 100 && item.count_comment > 10){ }}<span class="layui-badge">火</span> {{# } }}{{# if(item.article_top){ }}<span class="layui-badge layui-bg-blue">置顶</span> {{# } }}<a href="/detail/{{ item.article_code }}.html">{{ item.article_title }}</a></p><p class="layui-text">{{ item.article_synopsis }}</p></div></div><div class="layui-row layui-col-space3"><div class="layui-col-xs6 layui-col-sm2 layui-col-md2 layui-elip"><a href="/share/share.html#!type={{ item.type_code }}" data-type-code="{{ item.type_code }}" title="分类：{{ item.type_code }}"><i class="fa fa-tag"></i> {{ item.type_code }}</a></div><div class="layui-col-xs6 layui-col-sm3 layui-col-md2 layui-elip"><a title="作者：{{ item.user_nick_name }}"><i class="fa fa-user"></i> {{ item.user_nick_name }}</a></div><div class="layui-col-xs6 layui-col-sm4 layui-col-md3 layui-elip"><a title="时间：{{ util.timeAgo(item.article_time) }}"><i class="fa fa-clock-o"></i> {{ util.timeAgo(item.article_time) }}</a></div><div class="layui-col-xs6 layui-col-sm2 layui-col-md1 layui-col-md-offset3 layui-elip"><a title="浏览：{{ item.article_click }}"><i class="fa fa-eye"></i> {{ item.article_click }}</a></div><div class="layui-col-xs6 layui-col-sm1 layui-col-md1 layui-elip"><a href="/detail/{{ item.article_code }}.html#comment" title="评论：{{ item.count_comment }}"><i class="fa fa-commenting"></i> {{ item.count_comment }}</a></div></div>{{# }); }}</li></ul>'
    // 文章-发布-重置
    , HTML_OZQ_ADD_ARTICLE = '<div class="layui-row ozq-article-title"><h2 class="ozq-dblclick-edit">请双击这里输入您投稿的标题</h2><hr></div><div class="layui-row ozq-article-content"><p class="ozq-article-prompt">请拖拽左边的工具到此处编辑！</p></div>'
    // 动态
    , HTML_OZQ_DYNAMIC = '{{# layui.each(d.data.sysDynamics, function(index, item){ }}<li class="layui-timeline-item"><i class="layui-icon layui-timeline-axis">{{# if(index==0){ }}&#xe756;{{# }else{ }}&#xe63f;{{# } }}</i><div class="layui-timeline-content layui-text"><h3 class="layui-timeline-title">{{ util.timeAgo(item.dynamic_add_time) }} <span class="ozq-user-name">{{ item.user_nick_name }}</span></h3>{{ item.text_content }}</div></li>{{# }); }}'
    // 作品
    , HTML_OZQ_WORK = '{{# layui.each(d.data.sysWorks, function(index, item){ }}<div class="layui-col-xs12 layui-col-sm6 layui-col-md3"><div class="ozq-block"><img lay-src="{{ item.workCoverUrl }}" alt="{{ item.workTitle }}"><h2 class="layui-elip" title="{{ item.workTitle }}">{{ item.workTitle }}</h2><p class="layui-text" title="{{ item.workSynopsis }}">{{ item.workSynopsis }}</p><div>{{# if(!$.isEmptyObject(item.workDemoUrl)){ }}<a href="{{ item.workDemoUrl }}" target="_blank" class="layui-btn layui-btn-primary layui-btn-small"><i class="fa fa-eye fa-fw"></i> 演示</a>{{# } if(!$.isEmptyObject(item.workDownUrl)){ }}<a href="{{ item.workDownUrl }}" target="_blank" class="layui-btn layui-btn-primary layui-btn-small"><i class="fa fa-download fa-fw"></i> 下载</a>{{# } if($.isEmptyObject(item.workDemoUrl)&&$.isEmptyObject(item.workDownUrl)){ }}<a class="layui-btn layui-btn-primary layui-btn-small">暂无提供演示和下载地址！</a>{{# } }}</div></div></div>{{# }); }}'
    // 热门-博文
    , HTML_OZQ_HOT_ARTICLE = '{{# layui.each(d.data.sysArticles, function(index, item){ }}<div class="layui-row layui-col-space3"><div class="layui-col-xs1"><i class="fa fa-hand-o-right"></i></div><div class="layui-col-xs8 layui-elip"><a href="/detail/{{ item.article_code }}.html" title="{{ item.article_title }}" class="ozq-top-2">{{ item.article_title }}</a></div><div class="layui-col-xs3 layui-elip"><a title="浏览：{{ item.article_click }}"><i class="fa fa-eye"></i> {{ item.article_click }}</a></div></div>{{# }); }}'
    // 推荐-博文
    , HTML_OZQ_RECOMMEND_ARTICLE = '{{# layui.each(d.data.sysArticles, function(index, item){ }}<div class="layui-row layui-col-space3"><div class="layui-col-xs1"><i class="fa fa-hand-o-right"></i></div><div class="layui-col-xs11 layui-elip"><a href="/detail/{{ item.article_code }}.html" title="{{ item.article_title }}" class="ozq-top-2">{{ item.article_title }}</a></div></div>{{# }); }}'
    // 最新-博文
    , HTML_OZQ_NEW_ARTICLE = '{{# layui.each(d.data.sysArticles, function(index, item){ }}<div class="layui-row layui-col-space3"><div class="layui-col-xs1"><i class="fa fa-hand-o-right"></i></div><div class="layui-col-xs8 layui-elip"><a href="/detail/{{ item.article_code }}.html" title="{{ item.article_title }}" class="ozq-top-2">{{ item.article_title }}</a></div><div class="layui-col-xs3 layui-elip"><a title="时间：{{ util.timeAgo(item.article_time) }}"><i class="fa fa-clock-o"></i> {{ util.timeAgo(item.article_time) }}</a></div></div>{{# }); }}'
    // 热评用户
    , HTML_OZQ_HOT_USER = '{{# layui.each(d.data, function(index, item){ }}<div class="layui-row layui-col-space3"><div class="layui-col-xs1"><span class="layui-badge layui-bg-orange">{{ index+1 }}</span></div><div class="layui-col-xs3"><img lay-src="{{ item.user_figure_url }}" alt="{{ item.user_nick_name }}"></div><div class="layui-col-xs5 layui-elip">{{ item.user_nick_name }}</div><div class="layui-col-xs3 layui-elip"><a title="评论：{{ item.count_article }}"><i class="fa fa-commenting"></i> {{ item.count_article }}</a></div></div>{{# }); }}'
    // 评论或留言
    , HTML_OZQ_COMMENT = '<ul>{{# layui.each(d.data.sysComments, function(index, item){ }}<li data-user-code="{{ item.user_code }}" data-comment-code="{{ item.comment_code }}"><div class="layui-row layui-col-space10"><div class="layui-col-xs2 layui-col-sm1 ozq-head ozq-center"><img lay-src="{{ item.user_figure_url }}" alt="{{ item.user_nick_name }}"></div><div class="layui-col-xs10 layui-col-sm11"><p class="layui-elip"><span class="ozq-user-name">{{ item.user_nick_name }}</span></p><p class="layui-text">{{ item.text_content }}</p><p class="layui-elip"><a title="时间：{{ util.timeAgo(item.comment_add_time) }}"><i class="fa fa-clock-o"></i> {{ util.timeAgo(item.comment_add_time) }}</a><a class="ozq-user-reply"><i class="fa fa-commenting"></i> 回复</a></p></div></div>{{# if(item.hasOwnProperty(\'reply\')){ var replyUsers=item.reply.split(\';user_reply;\'); for (var ru = 0; ru< replyUsers.length; ru++) { var replyUser=replyUsers[ru]; }}<div class="layui-row ozq-comment-reply layui-col-space10"><div class="ozq-center layui-col-xs2 layui-col-sm1 ozq-head layui-col-xs-offset1"><img lay-src="{{ replyUser.substring(replyUser.indexOf(\'user_figure_url\')+\'user_figure_url\'.length,replyUser.indexOf(\'user_nick_name\')) }}" alt="{{ replyUser.substring(replyUser.indexOf(\'user_nick_name\')+\'user_nick_name\'.length,replyUser.indexOf(\'text_content\')) }}"></div><div class="layui-col-xs9 layui-col-sm10"><p class="layui-elip ozq-reply-title"><span class="ozq-user-name">{{ replyUser.substring(replyUser.indexOf(\'user_nick_name\')+\'user_nick_name\'.length,replyUser.indexOf(\'text_content\')) }}</span> 回复</p><p class="layui-text">{{ replyUser.substring(replyUser.indexOf(\'text_content\')+\'text_content\'.length,replyUser.indexOf(\'comment_add_time\')) }}</p><p class="layui-elip"><a title="时间：{{ util.timeAgo(replyUser.substring(replyUser.indexOf(\'comment_add_time\')+\'comment_add_time\'.length)*1000) }}"><i class="fa fa-clock-o"></i> {{ util.timeAgo(replyUser.substring(replyUser.indexOf(\'comment_add_time\')+\'comment_add_time\'.length)*1000) }}</a></p></div></div>{{# } }}{{# } }}</li>{{# }); }}</ul>'
    // 发表文章-图片
    , HTML_OZQ_IMG = '<img class="ozq-dblclick-edit" data-ozq-type="img" src="{{ d.src }}" lay-src="{{ d.src }}">'
    // 发表文章-工具
    , HTML_OZQ_ARTICLE_TOOL = '<div class="ozq-article-tool"><i class="fa fa-header" data-tool-type="header" draggable="true" title="段落标题"></i><i class="fa fa-text-width" data-tool-type="text" draggable="true" title="段落文本"></i><i class="fa fa-file-code-o" data-tool-type="code" draggable="true" title="代码片段"></i><i class="fa fa-file-image-o" data-tool-type="image" draggable="true" title="插入图片"></i><hr><i class="fa fa-long-arrow-up" title="段落上移"></i><i class="fa fa-long-arrow-down" title="段落下移"></i><i class="fa fa-trash-o" title="删除元素"></i><i class="fa fa-align-center" title="图片居中"></i></div>'
    // 发表文章-工具-段落标题
    , HTML_OZQ_HEADER_TOOL = '<h2 class="ozq-article-header ozq-dblclick-edit">请双击这里输入您的段落标题</h2>'
    // 发表文章-工具-段落文本
    , HTML_OZQ_TEXT_TOOL = '<div class="layui-text ozq-article-text ozq-dblclick-edit">请双击这里输入您的段落文本</div>'
    // 发表文章-工具-代码片段
    , HTML_OZQ_CODE_TOOL = '<pre class="layui-code ozq-dblclick-edit">请双击这里输入或拷贝代码到此处</pre>'
    // 发表文章-工具-文本-修改
    , HTML_OZQ_INPUT_EDIT = '<textarea type="text" class="ozq-input-edit"></textarea>'
    // 验证
    , HTML_OZQ_VALIDATE = '<div class="ozq-validate layui-form"><p>请输入下方的验证码验证！</p><div id="ozq-validate-show"></div><p><input type="text" autocomplete="off" class="layui-input"></p></div>'
    // 缓存
    , CAHE_USER = (fingerprint * 2 + 6) + ozq.v, CAHE_ARTICLE = (fingerprint * 3 + 5) + ozq.v, CAHE_COMMON = (fingerprint * 4 + 4) + ozq.v, CAHE_ARTICLE_TYPE = (fingerprint * 5 + 3) + ozq.v, CAHE_USER_REGISTER = (fingerprint * 6 + 2) + ozq.v;

    // 当前工具对象
    var Class = function()
    {
    };

    // 打印日志
    Class.prototype.log = function(m, stack)
    {
        if (ozq.mode)
        {
            console.log(m);
            if (stack)
            {
                var obj = {};
                Error.captureStackTrace(obj);
                console.log(obj.stack.split(/\n+/g)[2]);
            }
        }
    };

    // 清理老数据库
    Class.prototype.clearOldData = function()
    {
        var $this = this, oldStorage = window.localStorage;
        for (var olds = 0; olds < oldStorage.length; olds++)
        {
            var key = oldStorage.key(olds) + '' || '';
            if (!$this.endWith(key, ozq.v))
                oldStorage.removeItem(key);
        }
    };

    // 发送post请求
    Class.prototype.sendPost = function(url, params, callbackFun, errorFun)
    {
        var $this = this, params = params || {}, token = $('article.ozq-main[data-authen]').attr('data-authen') || '';
        if (token.length <= 0)
        {
            if ($.isFunction(errorFun))
                errorFun({
                    code    : -1,
                    message : '验证失败！'
                });
            else
                $this.log(errorFun || '获取信息失败，url：' + url + '失败\nparams：' + params + '！');
            return;
        }

        // timestamp,token,sign必须要有
        params['ozq.ke'] = token;
        params['ozq.ti'] = new Date().getTime();
        // sign一定要放在最后，因为不纳入编码
        params['ozq.si'] = sign.createSign(params);

        $.post(url, params, function(jsonDate, e)
        {
            if ($.isFunction(callbackFun))
                callbackFun(jsonDate, e);
            else
                $this.log(callbackFun || jsonDate);
        }, "json").error(function(jsonDate, e)
        {
            if ($.isFunction(errorFun))
                errorFun(jsonDate, e);
            else
                $this.log(errorFun || '获取信息失败，url：' + url + '失败\nparams：' + params + '！');
        });
    };

    // 扩展 某个字符串结尾
    Class.prototype.endWith = function(str, endStr)
    {
        var d = str.length - endStr.length;
        return (d >= 0 && str.lastIndexOf(endStr) == d);
    };

    // 清理缓存对象
    Class.prototype.clearCacheObj = function(key)
    {
        window.localStorage.removeItem(key);
        window.sessionStorage.removeItem(key);
    };

    // 自动调解-ozq-footer到底部
    Class.prototype.setFooter = function()
    {
        // 调整到底部
        var _window = $(window).height();
        var _outerHeight = $(document).outerHeight(true);
        $(ELE_OZQ_FOOTER).show().css('position', _outerHeight == _window ? 'absolute' : 'relative');
    };

    // 初始化我要打赏页面
    Class.prototype.initReward = function()
    {
        var $this = this;

        $(document).on('click', '.ozq-reward-btn', function()
        {
            layer.open({
                type       : 1,
                title      : false,
                shadeClose : true,
                skin       : 'ozq-reward',
                content    : '<div class="ozq-center layui-row">感谢您的支持，我会继续努力的!<br>扫码打赏，你说多少就多少</div><div class="ozq-center layui-row layui-col-space20"><div class="layui-col-xs6"><p><img alt="支付宝" src="/images/Alipay.png"></p><p>支付宝<br>打开支付宝扫一扫，即可进行扫码打赏哦</p></div><div class="layui-col-xs6"><p><img alt="微信" src="/images/WeChat.png"></p><p>微信<br>打开微信扫一扫，即可进行扫码打赏哦</p></div></div>'
            });
        });
    };

    // 初始化首页轮播图切换
    Class.prototype.initMainCarousel = function()
    {
        var $this = this, carouselObj = $(ELE_MAIN_CAROUSEL);
        if (carouselObj.length > 0)
        {
            var params = {
                'sysArticle.articleStatus' : 1,
                'sysArticle.articleMain'   : 1,
                'page.everyPage'           : 5,
                'page.currentPage'         : 1
            }, cacheData = $this.getCache(params);

            if (cacheData != null)
            {
                carouselObj.html(laytpl(HTML_OZQ_CAROUSEL).render(cacheData));
                carousel.render({
                    elem   : ELE_MAIN_CAROUSEL,
                    width  : '100%',
                    height : '230px',
                    anim   : 'fade',
                    arrow  : 'hover'
                });
                $this.refreshImgShow();
                return;
            }

            $this.sendPost(ozq.urls.listSysArticlePage, params, function(jsonDate, e)
            {
                if (jsonDate.code == 0)
                {
                    $this.putCache(params, jsonDate);
                    carouselObj.html(laytpl(HTML_OZQ_CAROUSEL).render(jsonDate));
                    carousel.render({
                        elem   : ELE_MAIN_CAROUSEL,
                        width  : '100%',
                        height : '230px',
                        anim   : 'fade',
                        arrow  : 'hover'
                    });
                    $this.refreshImgShow();
                }
            }, '首页轮播图-获取失败！');
        }
    };

    // 初始化图片懒加载
    Class.prototype.initLazyimg = function()
    {
        flow.lazyimg();
        this.refreshImgShow();
    };

    // 刷新当前页面图片懒加载
    Class.prototype.refreshImgShow = function()
    {
        $(document).scroll();
    };

    // 初始化到顶部工具
    Class.prototype.initUtilTop = function()
    {
        // 执行
        util.fixbar();
    };

    // 初始化到编辑器
    Class.prototype.initEdit = function(id)
    {
        return layedit.build(id, {
            height : 100,
            tool   : ['link', 'unlink', 'face']
        });
    };

    // 获取url地址中的参数
    Class.prototype.getQueryString = function(name)
    {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null)
            return unescape(r[2]);
        return null;
    }

    // 初始化界面事件
    Class.prototype.initEvent = function()
    {
        var $this = this;
        // QQ登录事件
        $this.qqLogin();

        // 页面响应
        $this.initPageResponse();
    };

    // 刷新页面code样式显示
    Class.prototype.toolCodeRender = function(elem)
    {
        code = layui.code({
            title  : "code",
            elem   : elem || '.ozq-layui-code',
            encode : true,
            about  : false
        });
    };

    // 插入图片
    Class.prototype.addOrModifyImg = function(val, targetObj, addOrModify)
    {
        layer.prompt({
            formType : 0,
            value    : val,
            title    : addOrModify ? '请输入图片的url' : '请输入需要修改图片的url'
        }, function(value, index, elem)
        {
            if (/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/.test(value) == true)
            {
                var html = laytpl(HTML_OZQ_IMG).render({
                    src : value
                });
                if (addOrModify)
                    targetObj.append(html);
                else
                    targetObj.replaceWith(html);
            } else
            {
                layer.msg(addOrModify ? '插入图片失败，不是合法的url！' : '修改图片失败，不是合法的url！');
            }
            layer.close(index);
        });
    };

    // 流加载文章列表
    Class.prototype.flowLoadArticle = function(hash)
    {
        var $this = this;
        flow.load({
            elem      : ELE_OZQ_ARTICLE,
            isLazyimg : true,
            mb        : 100,
            end       : '网友们正在努力投稿中...',
            done      : function(page, next)
            {
                var params = {
                    'sysArticle.articleStatus' : 1,
                    'sysArticle.typeCode'      : hash || location.hash.replace('#!type=', '') || '',
                    'page.everyPage'           : 9,
                    'page.currentPage'         : page
                }, cacheData = $this.getCache(params);

                if (cacheData != null)
                {
                    next(laytpl(HTML_OZQ_ARTICLE).render(cacheData), page < cacheData.data.page.totalPage);
                    return;
                }

                $this.sendPost(ozq.urls.listSysArticlePage, params, function(jsonDate, e)
                {
                    if (jsonDate.code == 0)
                    {
                        $this.putCache(params, jsonDate);
                        next(laytpl(HTML_OZQ_ARTICLE).render(jsonDate), page < jsonDate.data.page.totalPage);
                    } else
                        next('', page < 1);
                }, function()
                {
                    $this.log("文章-获取失败！");
                    next('', page < 1);
                });
            }
        });
    };

    // 公共读取缓存数据
    /**
     * 读取缓存数据
     * <p>
     * obj:缓存的key <br>
     * caheType:（可选，默认CAHE_COMMON）自定义缓存定义的类型<br>
     * millisecond:（可选，默认ozq.caches.overdueMillisecond）自定义失效时间,-1表示无限<br>
     * operation:（可选，默认window.localStorage）可选，window.localStorage，window.sessionStorage对象
     */
    Class.prototype.getCache = function(obj, caheType, millisecond, operation)
    {
        // 判断本地是否已经登录
        var $this = this, key = $this.hashCode(obj), storage = operation || window.localStorage, caheType = caheType || CAHE_COMMON, millisecond = millisecond || ozq.caches.overdueMillisecond, userJson = JSON.parse(unescape(storage.getItem(caheType) || "{}"));

        // 已经存在是否过期
        if (userJson.hasOwnProperty(key) && userJson[key].addTime)
        {
            var addTime = new Date(userJson[key].addTime).getTime(), serverTime = new Date().getTime(), dateSpan = serverTime - addTime;

            if (millisecond != -1 && dateSpan > millisecond)
            {
                delete userJson[key];
                storage.setItem(caheType, escape(JSON.stringify(userJson)));
            } else
                return userJson[key].data;
        }
        return null;
    };

    // 公共添加或更新缓存数据
    /**
     * 添加或更新缓存
     * <p>
     * obj:缓存的key <br>
     * value:对应的key值 <br>
     * caheType:（可选，默认CAHE_COMMON）自定义缓存定义的类型<br>
     * operation:（可选，默认window.localStorage）可选，window.localStorage，window.sessionStorage对象
     */
    Class.prototype.putCache = function(obj, value, caheType, operation)
    {
        // 判断本地是否已经登录
        var key = this.hashCode(obj), storage = operation || window.localStorage, caheType = caheType || CAHE_COMMON, userJson = JSON.parse(unescape(storage.getItem(caheType) || "{}"));
        userJson[key] = {
            data    : value,
            addTime : new Date().getTime()
        };
        storage.setItem(caheType, escape(JSON.stringify(userJson)));
    };

    // 获取当前元素的值
    Class.prototype.getEleVal = function(obj)
    {
        if (obj.next('.layui-form-radio').length > 0)
        {
            obj.each(function()
            {
                if ($(this).next('.layui-form-radio').is('.layui-form-radioed'))
                {
                    obj = $(this);
                    return false;
                }
            });
        } else if (obj.next('.layui-form-select').length > 0)
        {
            var $obj = obj.next('.layui-form-select').find('input');
            obj.find('option').filter('[text="' + $obj.val() + '"]').attr('selected', true);
        } else if (obj.next('.layui-form-checkbox').length > 0)
        {
            return obj.next('.layui-form-checkbox').is('.layui-form-checked');
        } else if (obj.next('.layui-form-switch').length > 0)
        {
            return obj.next('.layui-form-switch').is('.layui-form-onswitch');
        }
        return obj.val() || obj.text() || obj.html() || '';
    };

    // 公共hashCode 算法
    Class.prototype.hashCode = function(obj)
    {
        var str = obj, hash = 0, i, chr, len;

        if (typeof(obj) != 'string')
            str = JSON.stringify(obj);

        if (str.length === 0)
            return hash;

        for (i = 0, len = str.length; i < len; i++)
        {
            chr = str.charCodeAt(i);
            hash = ((hash << 5) - hash) + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    }

    // 初始化页面响应
    Class.prototype.initPageResponse = function(obj)
    {
        // 导航显示
        var $this = this, pathname = window.location.pathname || "/", typeBlog = $(ELE_TYPE_BLOG), article = $(ELE_OZQ_ARTICLE), hotBlog = $(ELE_OZQ_HOT_BLOG), recommendBlog = $(ELE_OZQ_RECOMMEND_BLOG), newBlog = $(ELE_OZQ_NEW_BLOG), hotUser = $(ELE_OZQ_HOT_USER), message = $(ELE_OZQ_MESSAGE), articleCode = $(ELE_OZQ_ADD_ARTICLE).attr('data-article-code') || "";

        // $(ELE_NAV + " " + ELE_NAV_ITEM).removeClass(ELE_LAYUI_THIS.substring(1));
        // $(ELE_NAV + ' a[href="' + pathname + '"]').closest('li' + ELE_NAV_ITEM).addClass(ELE_LAYUI_THIS.substring(1));

        // 文章分类，有就显示
        if (typeBlog.length > 0)
        {
            var typeBlogParams = {
                'sysType.orderBy' : ' type_sort asc '
            }, typeCacheData = $this.getCache(typeBlogParams, CAHE_ARTICLE_TYPE);

            if (typeCacheData != null)
            {
                typeBlog.append(laytpl(HTML_OZQ_TYPE).render(typeCacheData));
            } else
            {
                $this.sendPost(ozq.urls.listSysType, typeBlogParams, function(jsonDate, e)
                {
                    if (jsonDate.code == 0)
                    {
                        $this.putCache(typeBlogParams, jsonDate, CAHE_ARTICLE_TYPE);
                        typeBlog.append(laytpl(HTML_OZQ_TYPE).render(jsonDate));
                    }
                }, "文章分类-获取失败！");
            }
        }

        // 文章分类，点击a标签分类
        $(document).on('click', 'a[data-type-code]', function()
        {
            article.empty();
            $this.flowLoadArticle($(this).attr('data-type-code'));
        });

        // 文章
        if (article.length > 0)
        {
            $this.flowLoadArticle();
        }

        // 热门文章
        if (hotBlog.length > 0)
        {
            var hotBlogParams = {
                'sysArticle.articleStatus' : 1,
                'sysArticle.orderBy'       : ' article_click desc ',
                'sysArticle.typeCode'      : location.hash.replace('#!type=', '') || '',
                'page.everyPage'           : 6,
                'page.currentPage'         : 1
            }, hotBlogCacheData = $this.getCache(hotBlogParams);

            if (hotBlogCacheData != null)
            {
                hotBlog.find('div').remove();
                hotBlog.append(laytpl(HTML_OZQ_HOT_ARTICLE).render(hotBlogCacheData));
            } else
            {
                $this.sendPost(ozq.urls.listSysArticlePage, hotBlogParams, function(jsonDate, e)
                {
                    if (jsonDate.code == 0)
                    {
                        $this.putCache(hotBlogParams, jsonDate);
                        hotBlog.find('div').remove();
                        hotBlog.append(laytpl(HTML_OZQ_HOT_ARTICLE).render(jsonDate));
                    }
                }, "热门文章-获取失败！");
            }
        }

        // 推荐文章
        if (recommendBlog.length > 0)
        {
            var recommendBlogParams = {
                'sysArticle.articleStatus'  : 1,
                'sysArticle.articleKeyWord' : $('.ozq-article-title h2').text() || $('.ozq-article-title h2').html() || 'java',
                'page.everyPage'            : 10,
                'page.currentPage'          : 1
            }, recommendBlogCacheData = $this.getCache(recommendBlogParams);

            if (recommendBlogCacheData != null)
            {
                recommendBlog.find('div').remove();
                recommendBlog.append(laytpl(HTML_OZQ_RECOMMEND_ARTICLE).render(recommendBlogCacheData));
            } else
            {
                $this.sendPost(ozq.urls.listSysArticlePage, recommendBlogParams, function(jsonDate, e)
                {
                    if (jsonDate.code == 0)
                    {
                        $this.putCache(recommendBlogParams, jsonDate);
                        recommendBlog.find('div').remove();
                        recommendBlog.append(laytpl(HTML_OZQ_RECOMMEND_ARTICLE).render(jsonDate));
                    }
                }, "推荐文章-获取失败！");
            }
        }

        // 最新文章
        if (newBlog.length > 0)
        {
            var newBlogParams = {
                'sysArticle.articleStatus' : 1,
                'sysArticle.orderBy'       : ' article_time desc ',
                'sysArticle.typeCode'      : location.hash.replace('#!type=', '') || '',
                'page.everyPage'           : 6,
                'page.currentPage'         : 1
            }, newBlogCacheData = $this.getCache(newBlogParams);

            if (newBlogCacheData != null)
            {
                newBlog.find('div').remove();
                newBlog.append(laytpl(HTML_OZQ_NEW_ARTICLE).render(newBlogCacheData));
            } else
            {
                $this.sendPost(ozq.urls.listSysArticlePage, newBlogParams, function(jsonDate, e)
                {
                    if (jsonDate.code == 0)
                    {
                        $this.putCache(newBlogParams, jsonDate);
                        newBlog.find('div').remove();
                        newBlog.append(laytpl(HTML_OZQ_NEW_ARTICLE).render(jsonDate));
                    }
                }, "最新文章-获取失败！");
            }
        }

        // 热评用户
        if (hotUser.length > 0)
        {
            var hotUserParams = {
                'type'             : 'hotUser',
                'page.everyPage'   : 6,
                'page.currentPage' : 1
            }, hotUserCacheData = $this.getCache(hotUserParams);

            if (hotUserCacheData != null)
            {
                hotUser.find('div').remove();
                hotUser.append(laytpl(HTML_OZQ_HOT_USER).render(hotUserCacheData));
            } else
            {
                $this.sendPost(ozq.urls.listSysComment, hotUserParams, function(jsonDate, e)
                {
                    if (jsonDate.code == 0)
                    {
                        $this.putCache(hotUserParams, jsonDate);
                        hotUser.find('div').remove();
                        hotUser.append(laytpl(HTML_OZQ_HOT_USER).render(jsonDate));
                    }
                }, "热评用户-获取失败！");
            }
        }

        // 评论或留言
        if (message.length > 0)
        {
            var isMessage = $(ELE_OZQ_ADD_ARTICLE).length > 0 ? false : true, options = {
                elem   : KEY_COMMON_PAGE,
                count  : 0,
                groups : 3,
                curr   : location.hash.replace('#!' + KEY_PAGE_CURR + '=', ''),
                hash   : KEY_PAGE_CURR,
                layout : ['prev', 'page', 'next', 'skip'],
                jump   : function(obj)
                {
                    var messageParams = {
                        'sysComment.articleCode' : (isMessage ? '' : articleCode),
                        'sysComment.commentType' : (isMessage ? 3 : 1),
                        'page.everyPage'         : obj.limit,
                        'page.currentPage'       : obj.curr
                    }, messageCacheData = $this.getCache(messageParams);

                    if (messageCacheData != null)
                    {
                        $(ELE_OZQ_COMMENT).find('ul').remove();
                        $(ELE_OZQ_COMMENT).prepend(laytpl(HTML_OZQ_COMMENT).render(messageCacheData));
                        // 图片懒加载
                        $this.refreshImgShow();
                    } else
                    {
                        // 查询-评论和留言
                        $this.sendPost(ozq.urls.listSysCommentPage, messageParams, function(jsonDate, e)
                        {
                            if (jsonDate.code == 0)
                            {
                                $this.putCache(messageParams, jsonDate);
                                $(ELE_OZQ_COMMENT).find('ul').remove();
                                $(ELE_OZQ_COMMENT).prepend(laytpl(HTML_OZQ_COMMENT).render(jsonDate));
                                // 图片懒加载
                                $this.refreshImgShow();
                            }
                        }, "查询-评论和留言-获取失败！");
                    }
                }
            };

            // articleCode初始化评论或留言
            if (articleCode.length > 0 || isMessage)
            {
                // 查询-评论和留言
                var articleCodeParams = {
                    'sysComment.articleCode' : (isMessage ? '' : articleCode),
                    'sysComment.commentType' : (isMessage ? 3 : 1),
                    'page.everyPage'         : 10,
                    'page.currentPage'       : 1
                }, articleCodeCacheData = $this.getCache(articleCodeParams);

                if (articleCodeCacheData != null)
                {
                    options.count = articleCodeCacheData.data.page.totalCount;
                    $(ELE_OZQ_COMMENT).find('ul').remove();
                    $(ELE_OZQ_COMMENT).prepend(laytpl(HTML_OZQ_COMMENT).render(articleCodeCacheData));
                    // 图片懒加载
                    $this.refreshImgShow();
                    if (options.count > 0)
                        laypage.render(options);
                } else
                {
                    // 查询-评论和留言
                    $this.sendPost(ozq.urls.listSysCommentPage, articleCodeParams, function(jsonDate, e)
                    {
                        if (jsonDate.code == 0)
                        {
                            options.count = jsonDate.data.page.totalCount;
                            $this.putCache(articleCodeParams, jsonDate);
                            $(ELE_OZQ_COMMENT).find('ul').remove();
                            $(ELE_OZQ_COMMENT).prepend(laytpl(HTML_OZQ_COMMENT).render(jsonDate));
                            // 图片懒加载
                            $this.refreshImgShow();
                            if (options.count > 0)
                                laypage.render(options);
                        }
                    }, "查询-评论和留言-获取失败！");
                }
            }

            // 初始化是否可以发布博文
            var userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}"));
            if (!$.isEmptyObject(userJson.userCode))
            {
                $(ELE_OZQ_MESSAGE + ' fieldset.layui-field-title').html('<legend><span class="ozq-user-name">' + userJson.userNickName + '</span>，' + (isMessage ? '留下您的脚印' : '说说您的看法') + '！ </legend>');
                $(ELE_OZQ_MESSAGE + ' .ozq-article-operation').html('<button class="layui-btn ozq-article-submit">提交' + (isMessage ? '留言' : '评论') + '</button>');
                // 点击添加留言、评论
                $('.ozq-article-operation .ozq-article-submit').click(function()
                {
                    var verifyCode, layeditContent = layedit.getContent(layeditIndex);
                    layeditContent = layeditContent.replace(/img src/g, "img lay-src");
                    layeditContent = layeditContent.replace(/<p>/g, "");
                    layeditContent = layeditContent.replace(/<\/p>/g, "");
                    if (layeditContent.length < 4)
                    {
                        layer.msg('提交失败，多输入点内容吧！');
                        return false;
                    }
                    layer.open({
                        type     : 1,
                        content  : HTML_OZQ_VALIDATE,
                        btn      : ['提交', '取消'],
                        btnAlign : 'c',
                        title    : false,
                        success  : function(layero, index)
                        {
                            verifyCode = $this.getGVerify(KEY_VALIDATE_SHOW);
                        },
                        yes      : function(index, layero)
                        {
                            // 验证输入框的值
                            var inputCode = $(ELE_OZQ_VALIDATE + ' input').val();
                            if (verifyCode.validate(inputCode))
                            {
                                var params = {
                                    'sysComment.articleCode' : articleCode,
                                    'sysComment.userCode'    : userJson.userCode,
                                    'sysComment.commentType' : (isMessage ? 3 : 1),
                                    'sysComment.textCode'    : layeditContent
                                };
                                $this.sendPost(ozq.urls.addSysComment, params, function(jsonDate, e)
                                {
                                    if (jsonDate.code != 0)
                                        layer.alert(jsonDate.message || jsonDate.data || '提交失败，参数是否正常？', {
                                            icon : 2
                                        });
                                    else
                                    {
                                        $this.clearCacheObj(CAHE_COMMON);

                                        options.count = options.count || 1;
                                        laypage.render(options);

                                        // 清理当前的内容
                                        layeditIndex = $this.initEdit(KEY_MESSAGE_EDITOR);

                                        layer.alert('提交成功！', {
                                            icon : 1
                                        });
                                    }
                                }, function(jsonDate, e)
                                {
                                    layer.alert('提交失败，网络是否异常？', {
                                        icon : 2
                                    });
                                });
                            } else
                            {
                                layer.msg('提交失败，验证没有通过！');
                            }
                            layer.close(index);
                        }
                    });
                });

                // 回复评论或留言
                $(document).on('click', ELE_OZQ_MESSAGE + ' ' + ELE_OZQ_USER_REPLY, function()
                {
                    var replyObj = $(this);
                    // 删除
                    $('.ozq-textarea-edit').remove();
                    var htmlObj = $('<div class="layui-row layui-form ozq-textarea-edit"><textarea class="layui-textarea layui-hide" id="' + ELE_OZQ_USER_REPLY.substring(1) + '"></textarea><section class="layui-row ozq-article-operation"><button class="layui-btn">回复评论</button></section></div>');
                    replyObj.closest('div').append(htmlObj);

                    // 解析编辑框
                    var replyIndex = $this.initEdit(ELE_OZQ_USER_REPLY.substring(1)), oldUserCode = replyObj.closest('li').attr("data-user-code"), oldCommentCode = replyObj.closest('li').attr("data-comment-code");
                    htmlObj.find('.layui-btn').click(function()
                    {
                        var verifyCode, layeditContent = layedit.getContent(replyIndex);
                        layeditContent = layeditContent.replace(/img src/g, "img lay-src");
                        layeditContent = layeditContent.replace(/<p>/g, "");
                        layeditContent = layeditContent.replace(/<\/p>/g, "");
                        if (layeditContent.length < 4)
                        {
                            layer.msg('提交失败，多输入点内容吧！');
                            return false;
                        }
                        layer.open({
                            type     : 1,
                            content  : HTML_OZQ_VALIDATE,
                            btn      : ['提交', '取消'],
                            btnAlign : 'c',
                            title    : false,
                            success  : function(layero, index)
                            {
                                verifyCode = $this.getGVerify(KEY_VALIDATE_SHOW);
                            },
                            yes      : function(index, layero)
                            {
                                // 验证输入框的值
                                var inputCode = $(ELE_OZQ_VALIDATE + ' input').val();
                                if (verifyCode.validate(inputCode))
                                {
                                    var params = {
                                        'sysComment.articleCode'   : (isMessage ? '' : articleCode),
                                        'sysComment.userCode'      : oldUserCode,
                                        'sysComment.commentCode'   : oldCommentCode,
                                        'sysComment.commentType'   : (isMessage ? 4 : 2),
                                        'sysComment.userReplyCode' : userJson.userCode,
                                        'sysComment.textCode'      : layeditContent
                                    };
                                    $this.sendPost(ozq.urls.addSysComment, params, function(jsonDate, e)
                                    {
                                        if (jsonDate.code != 0)
                                            layer.alert(jsonDate.message || jsonDate.data || '提交失败，参数是否正常？', {
                                                icon : 2
                                            });
                                        else
                                        {
                                            var json = {
                                                data : {
                                                    sysComments : [{
                                                        user_figure_url : userJson.userFigureUrl,
                                                        user_code       : userJson.userCode,
                                                        user_nick_name  : userJson.userNickName,
                                                        text_content    : layeditContent,
                                                        reply           : 'user_figure_url' + userJson.userFigureUrl + 'user_nick_name' + userJson.userNickName + 'text_content' + layeditContent + 'comment_add_time' + jsonDate.data.commentAddTime
                                                    }]
                                                }
                                            };
                                            $('.ozq-textarea-edit').remove();
                                            replyObj.closest('li').append($(laytpl(HTML_OZQ_COMMENT).render(json)).find('li div.ozq-comment-reply:eq(0)'));
                                            $this.refreshImgShow();

                                            $this.clearCacheObj(CAHE_COMMON);
                                        }
                                    }, function(jsonDate, e)
                                    {
                                        layer.msg('提交失败，验证没有通过！');
                                    });
                                    layer.close(index);
                                }
                            }
                        });
                    });
                });
            } else
            {
                $(ELE_OZQ_MESSAGE + ' fieldset.layui-field-title').html('<legend>请点击右上方的QQ图标登录，登录后即可' + (isMessage ? '留言' : '评论') + '！</legend>');
                $(ELE_OZQ_MESSAGE + ' .ozq-article-operation').html('请点击右上角登录，登录后即可提交' + (isMessage ? '留言' : '评论') + '！<button class="layui-btn layui-btn-disabled">提交' + (isMessage ? '留言' : '评论') + '</button>');
            }
        }

        // 编辑页面
        if (pathname.indexOf('/share/article/') == 0)
            pathname = '/share/article.html';
        if (pathname.indexOf('/detail/') == 0)
            pathname = '/detail/article.html';
        switch (pathname)
        {
            // 首页
            case '/' :
                $this.pageIndex();
                break;
            // 分享-投稿-发布文章/修改
            case '/share/article.html' :
                $this.pageArticle();
                break;
            // 分享-投稿-文章详情
            case '/detail/article.html' :
                $this.pageDetailArticle();
                break;
            // 动态
            case '/common/dynamic.html' :
                $this.pageDynamic();
                break;
            // 动态-发布
            case '/user/dynamic.html' :
                $this.pageUserDynamic();
                break;
            // 作品
            case '/common/opus.html' :
                $this.pageOpus();
                break;
            // 作品-发布
            case '/user/opus.html' :
                $this.pageUserOpus();
                break;
            // 个人中心
            case '/user/my.html' :
                $this.pageMy();
                break;
            default :
        }
    };

    // 首页
    Class.prototype.pageIndex = function()
    {
        var $this = this, params = {
            'sysUser.orderBy'  : ' user_register_time desc ',
            'page.everyPage'   : 12,
            'page.currentPage' : 1
        }, cacheData = $this.getCache(params, CAHE_USER_REGISTER);

        if (cacheData != null)
        {
            $(ELE_NEW_USER + ' dl').remove();
            $(ELE_NEW_USER).append(laytpl(HTML_OZQ_NEW_USER).render(cacheData));
            // 图片懒加载
            $this.refreshImgShow();
        } else
        {
            // 查询-最新用户
            $this.sendPost(ozq.urls.listSysUserPage, params, function(jsonDate, e)
            {
                if (jsonDate.code == 0)
                {
                    $this.putCache(params, jsonDate, CAHE_USER_REGISTER);
                    $(ELE_NEW_USER + ' dl').remove();
                    $(ELE_NEW_USER).append(laytpl(HTML_OZQ_NEW_USER).render(jsonDate));
                    // 图片懒加载
                    $this.refreshImgShow();
                }
            }, '首页查询-最新用户-获取失败！');
        }
    };

    // 是否登录切换，数据为空表示没有登录
    Class.prototype.changeLogin = function(obj)
    {
        if ($.isEmptyObject(obj))
        {
            $(ELE_NAV_USER).html('<li class="layui-nav-item"><a href="/login/qq/to" class="ozq-login-qq" title="QQ登录"><i class="fa fa-qq fa-lg"></i></a></li>')
        } else
        {
            $(ELE_NAV_USER).html('<li class="layui-nav-item"><a href="/user/my.html" class="ozq-nav-avatar"><img src="' + obj.userFigureUrl + '" alt="' + obj.userNickName + '" title="' + obj.userNickName + '"></a></li>')
        }
    };

    // 发布动态和作品
    Class.prototype.addClickDynamicOrOpus = function()
    {
        var $this = this, userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}"));
        if (!$.isEmptyObject(userJson.userCode))
        {
            // 点击添加
            $(document).on('click', '.ozq-add-content .layui-btn', function()
            {
                var $click = $(this), $form = $click.closest('.layui-input-block').prev('.layui-form'), $type = $form.attr('data-name'), $action = ($type == 'sysDynamic' ? ozq.urls.addSysDynamic : ozq.urls.addSysWork);
                // 判断是重置还是提交
                if ($click.is('.layui-btn-danger'))
                {
                    // 重置
                    $form.find('[name]').val('');
                } else
                {
                    // 提交
                    var params = {}, isVerify = true, verifyCode, countPar = 0;
                    params[$type + '.userCode'] = userJson.userCode;
                    $form.find("[name]").each(function()
                    {
                        var $each = $(this), $eachForm = $each.closest('.layui-form-item'), bindNameVal = $('[data-bind-name="' + $eachForm.attr('data-bind-type') + '"]').val() || '', label = $eachForm.find('label.layui-form-label').text() || '', $name = $each.attr('name'), val = $this.getEleVal($each), nodeName = $each.prop("nodeName");
                        if ('textarea'.toLowerCase() == nodeName.toLowerCase())
                            val = val.replace(/\r|\n|\t/g, "&nbsp;").replace(/<(script.*)>(.*)<(\/script)>/ig, '&lt;$1&gt;$2&lt;$3&gt;');
                        if (val.length > 0)
                        {
                            if (label.indexOf("图片") >= 0 || label.indexOf("地址") >= 0)
                            {
                                if (/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/.test(val) == false)
                                {
                                    isVerify = false;
                                    layer.tips('请输入正确的地址(url)', $each, {
                                        tips : 1
                                    });
                                    return isVerify;
                                }
                            }
                            if (bindNameVal.length > 0)
                                bindNameVal = '<div>' + bindNameVal + '</div>';
                            switch (label)
                            {
                                case '图片地址' :
                                    val = '<div class="ozq-dynamic-img">' + bindNameVal + '<img lay-src="' + val + '" /></div>';
                                    break;
                                case '视频地址' :
                                    val = '<div class="ozq-dynamic-video">' + bindNameVal + '<video src="' + val + '" controls="controls">您的浏览器不支持该视频播放！</video></div>';
                                    break;
                                case '音乐地址' :
                                    val = '<div class="ozq-dynamic-audio">' + bindNameVal + '<audio src="' + val + '" controls="controls">您的浏览器不支持该音频播放！</audio></div>';
                                    break;
                                default :
                            }
                            params[$type + '.' + $name] = val;
                        }
                    });
                    if (!isVerify)
                        return isVerify;

                    for (var pa in params)
                        countPar++;

                    if (countPar < 3)
                    {
                        layer.msg('提交失败，请输入具体内容！');
                        return false;
                    }
                    layer.open({
                        type     : 1,
                        content  : HTML_OZQ_VALIDATE,
                        btn      : ['提交', '取消'],
                        btnAlign : 'c',
                        title    : false,
                        success  : function(layero, index)
                        {
                            verifyCode = $this.getGVerify(KEY_VALIDATE_SHOW);
                        },
                        yes      : function(index, layero)
                        {
                            // 验证输入框的值
                            var inputCode = $(ELE_OZQ_VALIDATE + ' input').val();
                            if (verifyCode.validate(inputCode))
                            {
                                $this.sendPost($action, params, function(jsonDate, e)
                                {
                                    if (jsonDate.code == 0)
                                    {
                                        layer.alert('提交成功，正在审核中...', {
                                            icon : 1
                                        });
                                        $form.find('[data-bind-name]').val('');
                                        $form.find('[name]').val('');
                                    } else
                                    {
                                        layer.alert(jsonDate.message || jsonDate.data || '提交失败，参数是否正常？', {
                                            icon : 2
                                        });
                                    }
                                }, '动态或作品提交失败');
                            } else
                            {
                                layer.msg('提交失败，验证没有通过！');
                            }
                            layer.close(index);
                        }
                    });
                }
            });
        }
    };

    // 动态-发布
    Class.prototype.pageUserDynamic = function()
    {
        var $this = this, userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}"));
        if (!$.isEmptyObject(userJson.userCode))
        {
            // 发布按钮
            $('.ozq-article-operation').html('<button class="layui-btn">提交动态</button><button class="layui-btn layui-btn-danger">重置动态</button>');

            // 监听动态显示
            form.on('select(dynamicType)', function(data)
            {
                $('.layui-form-item[data-bind-type]').hide();
                $('.layui-form-item[data-bind-type] [name="textCode"]').val('');
                $('.layui-form-item[data-bind-type="dynamicType_' + data.value + '"]').show();
            });

            $this.addClickDynamicOrOpus();
        } else
        {
            $('.ozq-article-operation').html('请点击右上角登录，登录后即可发布动态！<button class="layui-btn layui-btn-disabled">发布动态</button>');
        }
    };

    // 作品-发布
    Class.prototype.pageUserOpus = function()
    {
        var $this = this, userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}"));
        if (!$.isEmptyObject(userJson.userCode))
        {
            // 发布按钮
            $('.ozq-article-operation').html('<button class="layui-btn">提交作品</button><button class="layui-btn layui-btn-danger">重置作品</button>');

            $this.addClickDynamicOrOpus();
        } else
        {
            $('.ozq-article-operation').html('请点击右上角登录，登录后即可发布作品！<button class="layui-btn layui-btn-disabled">发布作品</button>');
        }
    };

    // 动态
    Class.prototype.pageDynamic = function()
    {
        var $this = this, userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}"));
        if (!$.isEmptyObject(userJson.userCode))
        {
            // 发布按钮
            $('.ozq-article-operation').html('<a href="/user/dynamic.html" class="layui-btn ozq-add-submit">发布动态</a>');
        } else
        {
            $('.ozq-article-operation').html('请点击右上角登录，登录后即可发布动态！<button class="layui-btn layui-btn-disabled">发布动态</button>');
        }

        // 流加载数据
        flow.load({
            elem      : '#ozq-timeline',
            isLazyimg : true,
            mb        : 100,
            end       : 'Ta的动态正在书写中...',
            done      : function(page, next)
            {
                var params = {
                    'sysDynamic.dynamicStatus' : 1,
                    'page.everyPage'           : 10,
                    'page.currentPage'         : page
                }, cacheData = $this.getCache(params);

                if (cacheData != null)
                {
                    next(laytpl(HTML_OZQ_DYNAMIC).render(cacheData), page < cacheData.data.page.totalPage);
                    return;
                }

                $this.sendPost(ozq.urls.listSysDynamicPage, params, function(jsonDate, e)
                {
                    if (jsonDate.code == 0)
                    {
                        $this.putCache(params, jsonDate);
                        next(laytpl(HTML_OZQ_DYNAMIC).render(jsonDate), page < jsonDate.data.page.totalPage);
                    } else
                        next('', page < 1);
                }, function()
                {
                    $this.log("动态-获取失败！");
                    next('', page < 1);
                });
            }
        });
    };

    // 用户中心
    Class.prototype.pageMy = function()
    {
        var $this = this, userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}"));
        if (!$.isEmptyObject(userJson.userCode))
        {
            $('.ozq-user-info').html(laytpl(HTML_OZQ_USER_INFO).render(userJson));
        } else
        {
            $('.ozq-user-info').html("请点击右上角的登录！");
        }

        // 点击退出登录
        $(document).on('click', '.ozq-user-info .ozq-quit', function()
        {
            window.localStorage.removeItem(CAHE_USER);
            $('.ozq-add-content').remove();
            $this.changeLogin();
            ozq.initUI();
            return false;
        });

        // 点击更新缓存
        $(document).on('click', '.ozq-user-info .ozq-update', function()
        {
            var params = {
                'caches[0]' : 'sysArticle',
                'caches[1]' : 'sysComment',
                'caches[2]' : 'sysDynamic',
                'caches[3]' : 'sysWork',
                'caches[4]' : 'sysText',
                'caches[5]' : 'sysUser',
                'caches[6]' : 'sysType'
            };
            $this.sendPost(ozq.urls.updateCache, params, function(jsonDate, e)
            {
                if (jsonDate.code == 0)
                {
                    layer.alert('更新服务缓存成功!', {
                        icon : 1
                    });
                } else
                {
                    layer.alert(jsonDate.message || jsonDate.data || '更新缓存失败，参数是否正常？', {
                        icon : 2
                    });
                }
            }, '更新服务缓存失败');
        });

        // 点击本地更新缓存
        $(document).on('click', '.ozq-user-info .ozq-local-update', function()
        {
            $this.clearCacheObj(CAHE_ARTICLE);
            $this.clearCacheObj(CAHE_ARTICLE_TYPE);
            $this.clearCacheObj(CAHE_COMMON);
            $this.clearCacheObj(CAHE_USER_REGISTER);
            layer.alert('更新本地缓存成功!', {
                icon : 1
            });
        });
    };

    // 作品
    Class.prototype.pageOpus = function()
    {
        var $this = this, userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}"));
        if (!$.isEmptyObject(userJson.userCode))
        {
            // 发布按钮
            $('.ozq-article-operation').html('<a href="/user/opus.html" class="layui-btn ozq-add-submit">发布作品</a>');
        } else
        {
            $('.ozq-article-operation').html('请点击右上角登录，登录后即可发布作品！<button class="layui-btn layui-btn-disabled">发布作品</button>');
        }

        flow.load({
            elem      : '#ozq-opus',
            isLazyimg : true,
            mb        : 100,
            end       : 'Ta的作品正在发布中...',
            done      : function(page, next)
            {
                var params = {
                    'sysWork.workStatus' : 1,
                    'sysWork.orderBy'    : ' work_add_time desc ',
                    'page.everyPage'     : 10,
                    'page.currentPage'   : page
                }, cacheData = $this.getCache(params);

                if (cacheData != null)
                {
                    next(laytpl(HTML_OZQ_WORK).render(cacheData), page < cacheData.data.page.totalPage);
                    return;
                }

                $this.sendPost(ozq.urls.listSysWorkPage, params, function(jsonDate, e)
                {
                    if (jsonDate.code == 0)
                    {
                        $this.putCache(params, jsonDate);
                        next(laytpl(HTML_OZQ_WORK).render(jsonDate), page < jsonDate.data.page.totalPage);
                    } else
                        next('', page < 1);
                }, function()
                {
                    $this.log("作品-获取失败！");
                    next('', page < 1);
                });
            }
        });

    };

    // 分享-投稿-文章-详情
    Class.prototype.pageDetailArticle = function()
    {
        var $this = this, userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}")), userCode = $(ELE_OZQ_ADD_ARTICLE).attr('data-user-code') || '';

        if (!$.isEmptyObject(userJson.userCode) && userCode == userJson.userCode)
        {
            $(ELE_OZQ_ADD_ARTICLE).find('.ozq-edit-hide').show();
        } else
        {
            $(ELE_OZQ_ADD_ARTICLE).find('.ozq-edit-hide').remove();
        }
    };

    // 分享-投稿-发布文章
    Class.prototype.pageArticle = function()
    {
        var $this = this, userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}")), pathname = window.location.pathname || "/", articleHtml = window.localStorage.getItem(CAHE_ARTICLE), userCode = $(ELE_OZQ_ADD_ARTICLE).attr('data-user-code') || '';

        // 初始化工具栏目
        layer.open({
            type      : 1,
            title     : '工具',
            skin      : ELE_ARTICLE_TOOL_STYLE.substring(1),
            area      : '77px',
            offset    : 'l',
            closeBtn  : 0,
            shade     : 0,
            anim      : -1,
            isOutAnim : false,
            resize    : false,
            content   : HTML_OZQ_ARTICLE_TOOL,
            success   : function(layero, index)
            {
                // 上移
                $(ELE_ARTICLE_TOOL + ' i.fa-long-arrow-up').click(function()
                {
                    var clickObj = $(ELE_ARTICLE_CLICK_BORDER), prevObj = clickObj.prev(ELE_DBLCLICK_EDIT);
                    if (clickObj.length > 0)
                    {
                        if (prevObj.length <= 0)
                            prevObj = clickObj.prev(ELE_OZQ_IMG);
                        if (prevObj.length <= 0)
                            prevObj = clickObj.parent(ELE_OZQ_IMG).prev(ELE_DBLCLICK_EDIT);

                        if (clickObj.parent(ELE_OZQ_IMG).length > 0)
                            clickObj = clickObj.parent(ELE_OZQ_IMG);

                        if (prevObj.length > 0)
                        {
                            clickObj.after(prevObj);
                        } else
                        {
                            layer.msg('上移失败，已经是最顶了！');
                        }
                    } else
                    {
                        layer.msg('上移失败，没有选中！');
                    }
                });

                // 下移
                $(ELE_ARTICLE_TOOL + ' i.fa-long-arrow-down').click(function()
                {
                    var clickObj = $(ELE_ARTICLE_CLICK_BORDER), prevObj = clickObj.next(ELE_DBLCLICK_EDIT);
                    if (clickObj.length > 0)
                    {
                        if (prevObj.length <= 0)
                            prevObj = clickObj.next(ELE_OZQ_IMG);
                        if (prevObj.length <= 0)
                            prevObj = clickObj.parent(ELE_OZQ_IMG).next(ELE_DBLCLICK_EDIT);

                        if (clickObj.parent(ELE_OZQ_IMG).length > 0)
                            clickObj = clickObj.parent(ELE_OZQ_IMG);

                        if (prevObj.length > 0)
                        {
                            clickObj.before(prevObj);
                        } else
                        {
                            layer.msg('下移失败，已经是最底了！');
                        }
                    } else
                    {
                        layer.msg('下移失败，没有选中！');
                    }
                });

                // 删除元素
                $(ELE_ARTICLE_TOOL + ' i.fa-trash-o').click(function()
                {
                    var clickObj = $(ELE_ARTICLE_CLICK_BORDER);
                    if (clickObj.length > 0)
                    {
                        layer.confirm('确定删除?', {
                            icon  : 3,
                            title : '提示'
                        }, function(index)
                        {
                            clickObj.remove();
                            layer.close(index);
                        });
                    } else
                    {
                        layer.msg('删除失败，没有选中！');
                    }
                });

                // 图片居中
                $(ELE_ARTICLE_TOOL + ' i.fa-align-center').click(function()
                {
                    var clickObj = $(ELE_ARTICLE_CLICK_BORDER), type = clickObj.attr(DATA_OZQ_TYPE) || '';
                    if (clickObj.length > 0)
                    {
                        if (type == "img")
                            if (clickObj.parent().is(ELE_OZQ_IMG))
                                clickObj.parent().replaceWith(clickObj);
                            else
                                clickObj.wrapAll('<div class="' + ELE_OZQ_IMG.substring(1) + '"></div>');
                        else
                            layer.msg('图片居中失败，请选择图片！');
                    } else
                    {
                        layer.msg('图片居中失败，没有选中！');
                    }
                });

                // 工具-拖动效果
                $(ELE_ARTICLE_TOOL + ' i').each(function()
                {
                    var toolI = $(this), dragObj = $(this)[0], type = toolI.attr('data-tool-type');

                    // 开始拖拽
                    dragObj.ondragstart = function(ev)
                    {
                        switch (type)
                        {
                            // 标题
                            case 'header' :
                                ev.dataTransfer.setData(RAG_KEY, HTML_OZQ_HEADER_TOOL);
                                break;
                            // 文本
                            case 'text' :
                                ev.dataTransfer.setData(RAG_KEY, HTML_OZQ_TEXT_TOOL);
                                break;
                            // 代码
                            case 'code' :
                                ev.dataTransfer.setData(RAG_KEY, HTML_OZQ_CODE_TOOL);
                                break;
                            // 插入图片
                            case 'image' :
                                // ev.dataTransfer.setData(RAG_KEY, 'image');
                                break;
                            default :
                        }
                        ev.dataTransfer.setData(RAG_TOOL_TYPE_KEY, type);
                        return true;
                    };

                    // 拖拽结束
                    dragObj.ondragend = function(ev)
                    {
                        ev.dataTransfer.clearData(RAG_KEY);
                        ev.dataTransfer.clearData(RAG_TOOL_TYPE_KEY);
                        return false
                    };
                });
            }
        });

        // 工具-拖拽-落下
        $(document).on('drop', ELE_ARTICLE_CONTENT, function(e)
        {
            var $drop = $(this), ev = e.originalEvent, tarObj = ev.target;
            ev.preventDefault();

            var data = ev.dataTransfer.getData(RAG_KEY), toolType = ev.dataTransfer.getData(RAG_TOOL_TYPE_KEY);

            $(ELE_ARTICLE_PROMPT).remove();

            switch (toolType)
            {
                // 插入图片
                case 'image' :
                    $this.addOrModifyImg('', $drop, true);
                    break;
                default :
                    $drop.append(data);
            }
        });

        // 拖拽元素进入目标元素头上的时候
        $(document).on('dragover', ELE_ARTICLE_CONTENT, function(e)
        {
            var ev = e.originalEvent;
            ev.preventDefault();
        });

        // 文字监听修改(双击事件)
        $(document).on('dblclick', ELE_DBLCLICK_EDIT, function(e)
        {
            var $dblclick = $(this), inputObj = $(HTML_OZQ_INPUT_EDIT);

            // 判断是否已经在编辑状态
            if ($dblclick.find('.ozq-input-edit').length > 0)
                return false;

            $dblclick.addClass('ozq-article-text-edit');

            // 判断元素是否图片
            var eleType = $dblclick.prop("tagName");
            if (eleType.toLowerCase() == 'img'.toLowerCase())
            {
                $this.addOrModifyImg($dblclick.attr('src') || $dblclick.attr('lay-src') || '', $dblclick, false);
                return false;
            }

            inputObj.val($dblclick.val() || $dblclick.text() || $dblclick.html() || "");

            $dblclick.html(inputObj);
            // 失去焦点
            inputObj.blur(function()
            {
                $dblclick.removeClass('ozq-article-text-edit');
                $dblclick.html($(this).val());
            });
        });

        // 点击
        $(document).on('click', ELE_ARTICLE_CONTENT + " " + ELE_DBLCLICK_EDIT, function(e)
        {
            $(ELE_ARTICLE_CLICK_BORDER).removeClass(ELE_ARTICLE_CLICK_BORDER.substring(1));
            $(this).addClass(ELE_ARTICLE_CLICK_BORDER.substring(1));
        });

        // 初始化是否可以发布博文
        if ((!$.isEmptyObject(userJson.userCode) && userCode.length <= 0) || (userCode.length > 0 && userCode == userJson.userCode))
        {
            $('.ozq-article-operation').html('<button class="layui-btn ozq-add-submit">提交投稿</button><button class="layui-btn layui-btn-danger ozq-add-reset">重置投稿</button>');
            // 点击添加博文
            $('.ozq-article-operation .ozq-add-submit').click(function()
            {
                // 修复 当前页面还在编辑状态
                $('.ozq-input-edit').blur();
                $('.ozq-input-edit').remove();

                var verifyCode;
                layer.open({
                    type     : 1,
                    content  : HTML_OZQ_VALIDATE,
                    btn      : ['提交', '取消'],
                    btnAlign : 'c',
                    title    : false,
                    success  : function(layero, index)
                    {
                        verifyCode = $this.getGVerify(KEY_VALIDATE_SHOW);
                    },
                    yes      : function(index, layero)
                    {
                        // 验证输入框的值
                        var inputCode = $(ELE_OZQ_VALIDATE + ' input').val();
                        if (verifyCode.validate(inputCode))
                        {
                            var htmlObj = $($(ELE_ARTICLE_CONTENT).prop("outerHTML"));
                            htmlObj.find('.layui-code').addClass('ozq-layui-code');
                            htmlObj.find(ELE_DBLCLICK_EDIT).removeClass(ELE_DBLCLICK_EDIT.substring(1));
                            htmlObj.find(ELE_ARTICLE_CLICK_BORDER).removeClass(ELE_ARTICLE_CLICK_BORDER.substring(1));
                            htmlObj.find('[class=""]').removeAttr('class');
                            htmlObj.find('img').each(function()
                            {
                                $(this).attr('lay-src', $(this).attr('src')).removeAttr('data-ozq-type').removeAttr('src');
                            });
                            var htmlSynopsis = htmlObj.html(), params = {
                                'sysArticle.articleTitle'    : $.trim($('.ozq-article-title .ozq-dblclick-edit').html()),
                                'sysArticle.articleSynopsis' : $.trim(htmlSynopsis),
                                'sysArticle.userCode'        : userJson.userCode,
                                'sysArticle.articleCode'     : $(ELE_OZQ_ADD_ARTICLE).attr('data-article-code') || ''
                            };
                            $this.sendPost(ozq.urls.addSysArticle, params, function(jsonDate, e)
                            {
                                if (jsonDate.code != 0)
                                    layer.alert(jsonDate.message || jsonDate.data || '提交失败，参数是否正常？', {
                                        icon : 2
                                    });
                                else
                                {
                                    layer.alert('提交成功，正在审核中...', {
                                        icon : 1
                                    });
                                    window.localStorage.removeItem(CAHE_ARTICLE);
                                    $(ELE_OZQ_ADD_ARTICLE).html(HTML_OZQ_ADD_ARTICLE);
                                }
                            }, function(jsonDate, e)
                            {
                                layer.alert('提交失败，网络是否异常？', {
                                    icon : 2
                                });
                            });
                        } else
                        {
                            layer.msg('提交失败，验证没有通过！');
                        }
                        layer.close(index);
                    }
                });
            });

            // 点击重置博文
            $('.ozq-article-operation .ozq-add-reset').click(function()
            {
                layer.confirm('确定重置(恢复到初始状态)?', function(index)
                {
                    window.localStorage.removeItem(CAHE_ARTICLE);
                    $(ELE_OZQ_ADD_ARTICLE).html(HTML_OZQ_ADD_ARTICLE);
                    layer.close(index);
                });
            });
        } else
        {
            $('.ozq-article-operation').html('请点击右上角登录，登录后即可提交博文！<button class="layui-btn layui-btn-disabled">提交投稿</button>');
        }

        // 动态保存数据和解析
        if (pathname.indexOf('/share/article/') >= 0)
        {
            // 修改文章
            $(ELE_OZQ_ADD_ARTICLE).find('img').addClass('ozq-dblclick-edit').attr('data-ozq-type', 'img');
            $(ELE_OZQ_ADD_ARTICLE).find('div.ozq-article-text,h2.ozq-article-header').addClass('ozq-dblclick-edit');
        } else if (articleHtml)
        {
            $(ELE_OZQ_ADD_ARTICLE).html(unescape(articleHtml));
        }
        $(ELE_OZQ_ADD_ARTICLE).bind("DOMNodeInserted", function(e)
        {
            window.localStorage.setItem(CAHE_ARTICLE, escape($(ELE_OZQ_ADD_ARTICLE).html()));
        });
    };

    // js生成验证码
    Class.prototype.getGVerify = function(id)
    {
        function GVerify(options)
        {
            // 创建一个图形验证码对象，接收options对象为参数
            this.options = { // 默认options参数值
                id       : "", // 容器Id
                canvasId : "verifyCanvas", // canvas的ID
                width    : "100", // 默认canvas宽度
                height   : "30", // 默认canvas高度
                type     : "blend", // 图形验证码默认类型blend:数字字母混合类型、number:纯数字、letter:纯字母
                code     : ""
            }

            if (Object.prototype.toString.call(options) == "[object Object]")
            {// 判断传入参数类型
                for (var i in options)
                { // 根据传入的参数，修改默认参数值
                    this.options[i] = options[i];
                }
            } else
            {
                this.options.id = options;
            }

            this.options.numArr = "2,3,4,5,6,7,8,9".split(",");
            this.options.letterArr = getAllLetter();

            this._init();
            this.refresh();
        };

        GVerify.prototype = {
            /** 版本号* */
            version  : '1.0.0',

            /** 初始化方法* */
            _init    : function()
            {
                var con = document.getElementById(this.options.id);
                var canvas = document.createElement("canvas");
                /*
                 * this.options.width = con.offsetWidth > 0 ? con.offsetWidth : "100"; this.options.height = con.offsetHeight > 0 ? con.offsetHeight : "30";
                 */
                canvas.id = this.options.canvasId;
                canvas.width = this.options.width;
                canvas.height = this.options.height;
                canvas.style.cursor = "pointer";
                canvas.innerHTML = "您的浏览器版本不支持canvas";
                con.appendChild(canvas);
                var parent = this;
                canvas.onclick = function()
                {
                    parent.refresh();
                }
            },

            /** 生成验证码* */
            refresh  : function()
            {
                this.options.code = '';
                var canvas = document.getElementById(this.options.canvasId);
                if (canvas.getContext)
                {
                    var ctx = canvas.getContext('2d');
                }
                ctx.textBaseline = "middle";

                ctx.fillStyle = randomColor(180, 240);
                ctx.fillRect(0, 0, this.options.width, this.options.height);

                if (this.options.type == "blend")
                { // 判断验证码类型
                    var txtArr = this.options.numArr.concat(this.options.letterArr);
                } else if (this.options.type == "number")
                {
                    var txtArr = this.options.numArr;
                } else
                {
                    var txtArr = this.options.letterArr;
                }

                for (var i = 1; i <= 4; i++)
                {
                    var txt = txtArr[randomNum(0, txtArr.length)];
                    this.options.code += txt;
                    ctx.font = '20px SimHei';
                    // ctx.font = randomNum(this.options.height/2, this.options.height) + 'px SimHei'; //随机生成字体大小
                    ctx.fillStyle = randomColor(50, 160); // 随机生成字体颜色
                    /*
                     * ctx.shadowOffsetX = randomNum(-3, 3); ctx.shadowOffsetY = randomNum(-3, 3);
                     */
                    ctx.shadowBlur = randomNum(-3, 3);
                    ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
                    var x = this.options.width / 5 * i;
                    var y = this.options.height / 2;
                    var deg = randomNum(-30, 30);
                    /** 设置旋转角度和坐标原点* */
                    ctx.translate(x, y);
                    ctx.rotate(deg * Math.PI / 180);
                    ctx.fillText(txt, 0, 0);
                    /** 恢复旋转角度和坐标原点* */
                    ctx.rotate(-deg * Math.PI / 180);
                    ctx.translate(-x, -y);
                }
                /** 绘制干扰线* */
                for (var i = 0; i < 4; i++)
                {
                    ctx.strokeStyle = randomColor(40, 180);
                    ctx.beginPath();
                    ctx.moveTo(randomNum(0, this.options.width / 2), randomNum(0, this.options.height / 2));
                    ctx.lineTo(randomNum(0, this.options.width / 2), randomNum(0, this.options.height));
                    ctx.stroke();
                }
                /** 绘制干扰点* */
                for (var i = 0; i < this.options.width / 4; i++)
                {
                    ctx.fillStyle = randomColor(0, 255);
                    ctx.beginPath();
                    ctx.arc(randomNum(0, this.options.width), randomNum(0, this.options.height), 1, 0, 2 * Math.PI);
                    ctx.fill();
                }
            },

            /** 验证验证码* */
            validate : function(code)
            {
                var verifyCode = code.toLowerCase();
                var v_code = this.options.code.toLowerCase();
                if (verifyCode == v_code)
                {
                    return true;
                } else
                {
                    return false;
                }
            }
        }

        /** 生成字母数组* */
        function getAllLetter()
        {
            var letterStr = "欧,增,奇,个,人,博,客,a,b,c,d,e,f,g,h,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
            return letterStr.split(",");
        }
        /** 生成一个随机数* */
        function randomNum(min, max)
        {
            return Math.floor(Math.random() * (max - min) + min);
        }
        /** 生成一个随机色* */
        function randomColor(min, max)
        {
            var r = randomNum(min, max);
            var g = randomNum(min, max);
            var b = randomNum(min, max);
            return "rgb(" + r + "," + g + "," + b + ")";
        }
        return new GVerify(id);
    };

    // QQ登录处理
    Class.prototype.qqLogin = function()
    {
        var $this = this;

        // 判断本地是否已经登录
        var userJson = JSON.parse(unescape(window.localStorage.getItem(CAHE_USER) || "{}"));

        // 已经存在是否过期
        if (userJson.addTime)
        {
            var addTime = new Date(userJson.addTime).getTime(), serverTime = new Date().getTime(), dateSpan = serverTime - addTime;

            var days = parseInt(dateSpan / (1000 * 60 * 60 * 24));
            if (days > ozq.caches.overdueDay)
            {
                window.localStorage.removeItem(CAHE_USER);
                $this.changeLogin();
                return false;
            }
        }

        if ($.isEmptyObject(userJson.userCode))
        {
            // 处理是否登录
            var state = $this.getQueryString('state');
            if (state != null)
            {
                var params = {
                    state : state
                };
                $this.sendPost(ozq.urls.getUser, params, function(jsonDate, e)
                {
                    if (jsonDate.code != 0)
                        layer.alert(jsonDate.message || jsonDate.data || '登录失败，参数是否正常？', {
                            icon : 2
                        });
                    else
                    {
                        jsonDate.data.addTime = new Date().getTime();
                        window.localStorage.setItem(CAHE_USER, escape(JSON.stringify(jsonDate.data)));
                        $this.changeLogin(jsonDate.data);

                        // 修复清理数据
                        $this.clearCacheObj(CAHE_ARTICLE);
                        $this.clearCacheObj(CAHE_COMMON);
                        $this.clearCacheObj(CAHE_ARTICLE_TYPE);
                        $this.clearCacheObj(CAHE_USER_REGISTER);

                        ozq.initUI();
                    }
                }, function(jsonDate, e)
                {
                    layer.alert('登录失败，网络是否异常？', {
                        icon : 2
                    });
                });
            }
        } else
            $this.changeLogin(userJson);

        // 点击登录
        $(document).on('click', ELE_LOGIN_QQ, function()
        {
            layer.msg('正在通过QQ登入', {
                icon : 16,
                time : 0
            });
            var href = window.location.protocol + "//" + window.location.host + window.location.port + window.location.pathname;
            $(this).attr("href", $(this).attr("href") + "?url=" + encodeURIComponent(href));
        });
    };

    // 主入口
    ready.run = function()
    {
        $ = jQuery;
        $.ozq = new Class();
    };
    ready.run();
}(window);

// 全局变量
var layer, form, element, carousel, flow, util, layedit, laypage, laytpl, code, layeditIndex;
// 引导
layui.define(['layer', 'element', 'carousel', 'flow', 'util', 'layedit', 'laypage', 'laytpl', 'code'], function(exports)
{
    layer = layui.layer, form = layui.form, element = layui.element, laypage = layui.laypage, carousel = layui.carousel, flow = layui.flow, util = layui.util, layedit = layui.layedit, laytpl = layui.laytpl;
    // 全局配置弹出框
    layer.config({
        shade : 0.01
    });
    ozq.initUI();
});